"# Introduction to JumpStart - Sentence Pair Classification"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "669fa5d4",
"metadata": {},
"source": [
"---\n",
"\n",
"This notebook's CI test result for us-west-2 is as follows. CI test results in other regions can be found at the end of the notebook. \n",
"\n",
"\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"id": "b57a74bc",
"metadata": {},
"source": [
"---\n",
"Welcome to Amazon [SageMaker JumpStart](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-jumpstart.html)! You can use JumpStart to solve many Machine Learning tasks through one-click in SageMaker Studio, or through [SageMaker JumpStart API](https://sagemaker.readthedocs.io/en/stable/overview.html#use-prebuilt-models-with-sagemaker-jumpstart). \n",
"\n",
"In this demo notebook, we demonstrate how to use the JumpStart API for Sentence Pair Classification. Sentence Pair Classification refers to classifying a pair of input sentence to one of the class labels of the training dataset. We demonstrate two use cases of Sentence Pair Classification models:\n",
"\n",
"* How to use a Transformer model pre-trained on English dataset, and fine-tuned on [QNLI](https://www.tensorflow.org/datasets/catalog/glue#glueqnli) dataset, to perform Natural Language Inference.\n",
"* How to fine-tune a pre-trained Transformer model to a custom dataset, and then run inference on the fine-tuned model.\n",
"\n",
"Note: This notebook was tested on ml.t3.medium instance in Amazon SageMaker Studio with Python 3 (Data Science) kernel and in Amazon SageMaker Notebook instance with conda_python3 kernel.\n",
"\n",
"---"
]
},
{
"cell_type": "markdown",
"id": "b4b73811",
"metadata": {},
"source": [
"1. [Set Up](#1.-Set-Up)\n",
"2. [Select a pre-trained model](#2.-Select-a-pre-trained-model)\n",
"3. [Run inference on the pre-trained model](#3.-Run-inference-on-the-pre-trained-model)\n",
" * [Retrieve JumpStart Artifacts & Deploy an Endpoint](#3.1.-Retrieve-JumpStart-Artifacts-&-Deploy-an-Endpoint)\n",
" * [Example input sentences for inference](#3.2.-Example-input-sentences-for-inference)\n",
" * [Query endpoint and parse response](#3.3.-Query-endpoint-and-parse-response)\n",
" * [Clean up the endpoint](#3.4.-Clean-up-the-endpoint)\n",
"4. [Finetune the pre-trained model on a custom dataset](#4.-Finetune-the-pre-trained-model-on-a-custom-dataset)\n",
" * [Retrieve JumpStart Training artifacts](#4.1.-Retrieve-JumpStart-Training-artifacts)\n",
" * [Set Training parameters](#4.2.-Set-Training-parameters)\n",
" * [Train with Automatic Model Tuning (HPO)](#AMT)\n",
" * [Start Training](#4.4.-Start-Training)\n",
" * [Deploy & run Inference on the fine-tuned model](#4.5.-Deploy-&-run-Inference-on-the-fine-tuned-model)"
]
},
{
"cell_type": "markdown",
"id": "c79f3644",
"metadata": {},
"source": [
"## 1. Set Up\n",
"***\n",
"Before executing the notebook, there are some initial steps required for setup. This notebook requires latest version of sagemaker and ipywidgets.\n",
"To train and host on Amazon SageMaker, we need to setup and authenticate the use of AWS services. Here, we use the execution role associated with the current notebook instance as the AWS account role with SageMaker access. It has necessary permissions, including access to your data in S3. \n",
"\n",
"---"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "73573043",
"metadata": {},
"outputs": [],
"source": [
"import sagemaker, boto3, json\n",
"from sagemaker import get_execution_role\n",
"\n",
"aws_role = get_execution_role()\n",
"aws_region = boto3.Session().region_name\n",
"sess = sagemaker.Session()"
]
},
{
"cell_type": "markdown",
"id": "f713508e",
"metadata": {},
"source": [
"## 2. Select a pre-trained model\n",
"***\n",
"You can continue with the default model, or can choose a different model from the dropdown generated upon running the next cell. A complete list of JumpStart models can also be accessed at [JumpStart Models](https://sagemaker.readthedocs.io/en/stable/doc_utils/jumpstart.html#).\n",
"[Optional] Select a different JumpStart model. Here, we download jumpstart model_manifest file from the jumpstart s3 bucket, filter-out all the Sentence Pair Classification models and select a model.\n",
"display(IPython.display.Markdown(\"## Select a JumpStart pre-trained model from the dropdown below\"))\n",
"display(dropdown)"
]
},
{
"cell_type": "markdown",
"id": "27039ad1",
"metadata": {},
"source": [
"## 3. Run inference on the pre-trained model\n",
"***\n",
"Using JumpStart, we can perform inference on the pre-trained model, even without fine-tuning it first on a custom dataset. For this example, that means on a pair of input sentences predicting the class label from one of the 2 classes of the [QNLI](https://www.tensorflow.org/datasets/catalog/glue#glueqnli) dataset: entail, no-entail.\n",
"\n",
"***"
]
},
{
"cell_type": "markdown",
"id": "e9186664",
"metadata": {},
"source": [
"### 3.1. Retrieve JumpStart Artifacts & Deploy an Endpoint\n",
"***\n",
"We retrieve the deploy_image_uri, deploy_source_uri, and base_model_uri for the pre-trained model. To host the pre-trained model, we create an instance of [`sagemaker.model.Model`](https://sagemaker.readthedocs.io/en/stable/api/inference/model.html) and deploy it.\n",
"# Create the SageMaker model instance. Note that we need to pass Predictor class when we deploy model through Model class,\n",
"# for being able to run inference through the SageMaker API.\n",
"model = Model(\n",
" image_uri=deploy_image_uri,\n",
" source_dir=deploy_source_uri,\n",
" model_data=base_model_uri,\n",
" entry_point=\"inference.py\",\n",
" role=aws_role,\n",
" predictor_cls=Predictor,\n",
" name=endpoint_name,\n",
")\n",
"# deploy the Model.\n",
"base_model_predictor = model.deploy(\n",
" initial_instance_count=1,\n",
" instance_type=inference_instance_type,\n",
" endpoint_name=endpoint_name,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "8db81fa4",
"metadata": {},
"source": [
"### 3.2. Example input sentences for inference\n",
"***\n",
"Let's put in some example sentence pairs. You can put in any pairs of sentences, the model will predict whether the second sentence entails the first sentence or not.\n",
"These examples are taken from QNLI dataset downloaded from [TensorFlow](https://www.tensorflow.org/datasets/catalog/glue#glueqnli). [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). [Dataset Homepage](https://rajpurkar.github.io/SQuAD-explorer/). [CC BY-SA 4.0 License](https://creativecommons.org/licenses/by-sa/4.0/legalcode).\n",
"***"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c122353f",
"metadata": {},
"outputs": [],
"source": [
"sentence_pair1 = [\n",
" \"How many octaves does Beyonce have?\",\n",
" \"Beyoncé's vocal range spans four octaves.\",\n",
"]\n",
"sentence_pair2 = [\n",
" \"How many octaves does Beyonce have?\",\n",
" \"While another critic says she is a \"\n",
" \"Vocal acrobat, being able to sing long and complex melismas and vocal runs effortlessly, and in key.\",\n",
"]"
]
},
{
"cell_type": "markdown",
"id": "ec89c2fa",
"metadata": {},
"source": [
"### 3.3. Query endpoint and parse response\n",
"***\n",
"Input to the endpoint is a pair of sentences. Response from the endpoint is a dictionary containing the predicted class label, and a list of class label probabilities.\n",
"# Delete the SageMaker endpoint and the attached resources\n",
"base_model_predictor.delete_model()\n",
"base_model_predictor.delete_endpoint()"
]
},
{
"cell_type": "markdown",
"id": "0895a89d",
"metadata": {},
"source": [
"## 4. Finetune the pre-trained model on a custom dataset\n",
"***\n",
"Previously, we saw how to run inference on a pre-trained model, which was fine-tuned on QNLI dataset. Next, we discuss how a model can be finetuned to a custom dataset. \n",
"\n",
"The Text Embedding model can be fine-tuned on any sentence pair \n",
"classification dataset in the same way the model available for inference \n",
"has been fine-tuned on the QNLI dataset.\n",
"The model available for fine-tuning attaches a binary classification layer to the Text Embedding model\n",
"and initializes the layer parameters to random values. The fine-tuning step fine-tunes \n",
"all the model parameters to minimize prediction error on the input data and returns the fine-tuned model.\n",
"The model returned by fine-tuning can be further deployed for inference. Below are the instructions \n",
"for how the training data should be formatted for input to the model. \n",
"\n",
"- **Input:** A directory containing a 'data.csv' file. \n",
" - Each row of the first column of 'data.csv' should have 0/1 integer class labels.\n",
" - Each row of the second column should have the corresponding first sentence. \n",
" - Each row of the third column should have the corresponding second sentence. \n",
"- **Output:** A trained model that can be deployed for inference. \n",
"\n",
"Below is an example of 'data.csv' file showing values in its first three columns. Note that the file should not have any header.\n",
"\n",
"| | | |\n",
"|---|---|---|\n",
"|0\t|What is the Grotto at Notre Dame?\t|Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection.|\n",
"|1\t|What is the Grotto at Notre Dame?\t|It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858.|\n",
"|0\t|What sits on top of the Main Building at Notre Dame?\t|Atop the Main Building's gold dome is a golden statue of the Virgin Mary.|\n",
"### 4.1. Retrieve JumpStart Training artifacts\n",
"***\n",
"Here, for the selected model, we retrieve the training docker container, the training algorithm source, the pre-trained model, and a python dictionary of the training hyper-parameters that the algorithm accepts with their default values. Note that the model_version=\"*\" fetches the latest model. Also, we do need to specify the training_instance_type to fetch train_image_uri.\n",
"Now that we are done with all the setup that is needed, we are ready to fine-tune our Sentence Pair Classification model. To begin, let us create a [``sagemaker.estimator.Estimator``](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html) object. This estimator will launch the training job. \n",
"\n",
"There are two kinds of parameters that need to be set for training. \n",
"\n",
"The first one are the parameters for the training job. These include: (i) Training data path. This is S3 folder in which the input data is stored, (ii) Output path: This the s3 folder in which the training output is stored. (iii) Training instance type: This indicates the type of machine on which to run the training. Typically, we use GPU instances for these training. We defined the training instance type above to fetch the correct train_image_uri. \n",
"\n",
"The second set of parameters are algorithm specific training hyper-parameters.\n",
"***"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "126f7100",
"metadata": {},
"outputs": [],
"source": [
"# Sample training data is available in this bucket\n",
"For algorithm specific hyper-parameters, we start by fetching python dictionary of the training hyper-parameters that the algorithm accepts with their default values. This can then be overridden to custom values.\n",
"***"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "20818a89",
"metadata": {},
"outputs": [],
"source": [
"from sagemaker import hyperparameters\n",
"\n",
"# Retrieve the default hyper-parameters for fine-tuning the model\n",
"# [Optional] Override default hyperparameters with custom values\n",
"hyperparameters[\"batch-size\"] = \"64\"\n",
"print(hyperparameters)"
]
},
{
"cell_type": "markdown",
"id": "4042f56a",
"metadata": {
"collapsed": false
},
"source": [
"### 4.3. Train with Automatic Model Tuning ([HPO](https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning.html)) <a id='AMT'></a>\n",
"***\n",
"Amazon SageMaker automatic model tuning, also known as hyperparameter tuning, finds the best version of a model by running many training jobs on your dataset using the algorithm and ranges of hyperparameters that you specify. It then chooses the hyperparameter values that result in a model that performs the best, as measured by a metric that you choose. We will use a [HyperparameterTuner](https://sagemaker.readthedocs.io/en/stable/api/training/tuner.html) object to interact with Amazon SageMaker hyperparameter tuning APIs.\n",
"# You can select from the hyperparameters supported by the model, and configure ranges of values to be searched for training the optimal model.(https://docs.aws.amazon.com/sagemaker/latest/dg/automatic-model-tuning-define-ranges.html)\n",
"## 4.5. Deploy & run Inference on the fine-tuned model\n",
"***\n",
"A trained model does nothing on its own. We now want to use the model to perform inference. For this example, that means predicting the class label of an input sentence. We follow the same steps as in [3. Run inference on the pre-trained model](#3.-Run-inference-on-the-pre-trained-model). We start by retrieving the jumpstart artifacts for deploying an endpoint. However, instead of base_predictor, we deploy the `spc_estimator` that we fine-tuned.\n",
"***"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6d912eb2",
"metadata": {},
"outputs": [],
"source": [
"inference_instance_type = \"ml.m5.xlarge\"\n",
"\n",
"# Retrieve the inference docker container uri\n",
"# Use the estimator from the previous step to deploy to a SageMaker endpoint\n",
"finetuned_predictor = (hp_tuner if use_amt else spc_estimator).deploy(\n",
" initial_instance_count=1,\n",
" instance_type=inference_instance_type,\n",
" entry_point=\"inference.py\",\n",
" image_uri=deploy_image_uri,\n",
" source_dir=deploy_source_uri,\n",
" endpoint_name=endpoint_name,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "b64055c0",
"metadata": {},
"source": [
"---\n",
"Let's put in some example sentence pairs. You can put in any pairs of sentences, the model will predict whether the second sentence entails the first sentence or not.\n",
"These examples are taken from QNLI dataset downloaded from [TensorFlow](https://www.tensorflow.org/datasets/catalog/glue#glueqnli). [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0). [Dataset Homepage](https://rajpurkar.github.io/SQuAD-explorer/). [CC BY-SA 4.0 License](https://creativecommons.org/licenses/by-sa/4.0/legalcode).\n",
"---"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9d14b6ae",
"metadata": {},
"outputs": [],
"source": [
"sentence_pair1 = [\n",
" \"How many octaves does Beyonce have?\",\n",
" \"Beyoncé's vocal range spans four octaves.\",\n",
"]\n",
"sentence_pair2 = [\n",
" \"How many octaves does Beyonce have?\",\n",
" \"While another critic says she is a \"\n",
" \"Vocal acrobat, being able to sing long and complex melismas and vocal runs effortlessly, and in key.\",\n",
"]"
]
},
{
"cell_type": "markdown",
"id": "27cbadb9",
"metadata": {},
"source": [
"---\n",
"Next, we query the finetuned model, parse the response and print the predictions.\n",
"# Delete the SageMaker endpoint and the attached resources\n",
"finetuned_predictor.delete_model()\n",
"finetuned_predictor.delete_endpoint()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "4466ebda",
"metadata": {},
"source": [
"## Notebook CI Test Results\n",
"\n",
"This notebook was tested in multiple regions. The test results are as follows, except for us-west-2 which is shown at the top of the notebook.\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n"